import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_smart_heating/common/http.dart';
import 'package:flutter_smart_heating/config/config.dart';

import '../ui.dart';

class UiVerificationCode extends StatefulWidget {
  const UiVerificationCode({
    super.key,
    required this.account,
    this.scene = 'code',
    this.builder,
    this.params,
    this.totalTime = Config.codeCountDownTime,
    this.url = '/api/user/verification_code/send',
    this.fieldName = 'username',
    this.buttonText = '获取验证码',
    this.requiredText = '请先输入手机号码',
    this.countDownText = '%ss',
    this.onTimeOut,
    this.fontSize = 15,
  });

  /// 帐号，如手机号或者邮箱
  final String Function()? account;

  /// 场景
  final String scene;

  /// 发送时间间隔
  final int totalTime;

  /// 接口请求地址
  final String url;

  /// 帐号字段名称
  final String fieldName;

  /// 按钮文案
  final String buttonText;

  /// 倒计时文案
  /// 默认为 10s
  final String countDownText;

  /// 提示文案
  final String requiredText;

  /// 文字大小
  final double fontSize;

  /// 附件参数
  final Map<String, dynamic>? params;

  /// 自定义builder
  final Widget Function(UiVerificationCodeState state)? builder;

  /// 倒计时结束
  final Function()? onTimeOut;
  @override
  State<UiVerificationCode> createState() => UiVerificationCodeState();
}

class UiVerificationCodeState extends State<UiVerificationCode> {
  int time = 0;
  Timer? codeTimer;
  bool loading = false;
  @override
  void dispose() {
    codeTimer?.cancel();
    super.dispose();
  }

  /// 获取验证码
  getCode() async {
    String username = widget.account?.call() ?? '';
    if (username == '') {
      return Ui.toast(widget.requiredText);
    }
    setState(() {
      loading = true;
    });
    var res = await Http.instance.post(
      widget.url,
      data: {widget.fieldName: username, ...widget.params ?? {}},
    );
    setState(() {
      loading = false;
    });
    if (res.code == 1) {
      time = widget.totalTime;
      startTimer();
    }
    Ui.toast(res.msg);
  }

  /// 验证码获取倒计时
  startTimer() {
    codeTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (time < 1) {
        widget.onTimeOut?.call();
        return timer.cancel();
      }
      time--;
      setState(() {
        time;
      });
    });
  }

  bool get disabled => time > 0 || loading;

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (p0, p1) {
        return widget.builder?.call(this) ??
            TextButton(
              onPressed: disabled ? null : getCode,
              style: ButtonStyle(
                textStyle: MaterialStateProperty.resolveWith(
                  (states) => const TextStyle(
                    fontWeight: FontWeight.w300,
                    fontFamily: UiTheme.fontFamily,
                  ),
                ),
                overlayColor: Ui.createTextBtnBgColor(),
              ),
              child: loading
                  ? SizedBox(
                      height: p1.maxHeight * 0.4,
                      width: p1.maxHeight * 0.4,
                      child: const CircularProgressIndicator(
                        strokeWidth: 3,
                      ),
                    )
                  : Text(
                      time == 0
                          ? widget.buttonText
                          : widget.countDownText.replaceFirst(
                              '%s',
                              time.toString(),
                            ),
                      style: TextStyle(fontSize: widget.fontSize),
                    ),
            );
      },
    );
  }
}
